﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.ServiceModel;
using System.Messaging;
using System.Configuration;
using System.Threading;
using TPTecnicas.MessageProcessor.Email.Receiver.MessageProcessorService;
using TPTecnicas.MessageConnection;
using TPTecnicas.MessageProcessor.Common;
using System.Xml;
using TPTecnicas.MessageProcessor.Business;

namespace TPTecnicas.MessageProcessor.Email.Receiver
{
    partial class EmailReceiver : ServiceBase
    {
		public string XMLConfigPath { get; set; }
		public XmlDocument XMLConfig { get; set; }

		private Thread _reveiverThread;
        private MessageProcessorServiceClient _processorClient;
		private List<Account> _accounts;


		/// <summary>
		/// 
		/// </summary>
        public EmailReceiver()
        {
			Utils.Log("0, EmailReceiver, Se inicia el servicio");

			XMLConfig = new XmlDocument();
			XMLConfigPath = "C:/MailsAccounts.xml";			

            InitializeComponent();
			XMLConfig.Load(XMLConfigPath);
			_accounts = new List<Account>();
			ProcessXML();			
        }


        protected override void OnStart(string[] args)
        {
            var reveiveMailsMethod = new ThreadStart(ReceiveMails);
            _reveiverThread = new Thread(reveiveMailsMethod);
            _reveiverThread.Start();

            _processorClient = new MessageProcessorServiceClient();
        }


		private void ProcessXML()
		{
			XmlNodeList nServer, nSocket, nMail, nPassword;
			try
			{

				XmlNodeList mailAccounts = XMLConfig.GetElementsByTagName("MailAccounts");
				XmlNodeList lista = ((XmlElement)mailAccounts[0]).GetElementsByTagName("account");
				if (lista.Count >= 1)
				{
					foreach (XmlElement nodo in lista)
					{
						nServer = nodo.GetElementsByTagName("server");
						nSocket= nodo.GetElementsByTagName("socket");
						nMail= nodo.GetElementsByTagName("mail");
						nPassword = nodo.GetElementsByTagName("password");

						_accounts.Add(new Account(nServer[0].InnerText, int.Parse(nSocket[0].InnerText), nMail[0].InnerText, nMail[0].InnerText));
						Utils.Log("1, ProcessXML, Se agrega la account de server: " + nServer[0].InnerText);
						Utils.Log("1, ProcessXML, Se agrega la account de user: " + nMail[0].InnerText);
						Debugger.Log(1, "ProcessXML", "Se agrega la account: " + nServer[0].InnerText);
					}
				}
			}
			catch (Exception)
			{						
				throw;
			}
		}

        private void ReceiveMails()
        {
            while (true)
            {
                try
                {
                    Thread.Sleep(int.Parse(ConfigurationManager.AppSettings["WaitingInterval"]));
										
					Account a;
					int cont = 0;
					TPTecnicas.MessageProcessor.Common.Message mail;
					POP3LibraryWrapper obj = new POP3LibraryWrapper();
					
					do
					{
						a = _accounts[cont];
						obj.Connect(a);

						mail = Utils.RxMessageToMessage(obj.GetLastMail());

						obj.Disconnect();
						cont++;

						Utils.Log("1, ReceiveMails, Se conecta a cuenta: " + a.Mail + " " + obj.IsConnected.ToString());
					}
					while ((_accounts.Count <= cont) && (mail != null));

                    _processorClient.ProcessMessage(new TPTecnicas.MessageProcessor.Common.Message());
                }
                catch (Exception ex)
                {
                    continue;
                }
            }
        }

        protected override void OnStop()
        {
           
            try
            {
                _reveiverThread.Abort();
            }
            catch (Exception ex)
            {

            }
        }
    }
}
